package com.logic.landseaserver.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.landseaserver.common.VariableChar;
import com.logic.landseaserver.common.enums.*;
import com.logic.landseaserver.domain.*;
import com.logic.landseaserver.models.authcode.bean.UsedAuthCode;
import com.logic.landseaserver.persistence.read.*;
import com.logic.landseaserver.persistence.write.*;
import com.logic.landseaserver.service.*;
import com.logic.landseaserver.ws.dto.*;
import com.logic.system.domain.Configuration;
import com.logic.system.service.IConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.common.ws.dto.system.FileDTO;
import com.logic.landseaserver.common.LandeaConstants;
import com.logic.landseaserver.common.LandeaConstants.BillType;
import com.logic.landseaserver.common.LandeaConstants.ProduceType;
import com.logic.landseaserver.common.LandeaConstants.QueryUesdCodeType;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.config.DipositPDFConfiguration;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.FileTool;
import com.logic.landseaserver.common.util.PDF2Image;
import com.logic.landseaserver.models.authcode.bean.AddCouponUesd;
import com.logic.landseaserver.models.authcode.service.AuthCodeService;
import com.logic.landseaserver.models.authcode.service.CouponUsedService;
import com.logic.landseaserver.models.independent.service.BillIndependentService;
import com.logic.landseaserver.models.payment.PaymentConstant;
import com.logic.landseaserver.models.payment.PaymentConstant.BillPaymentStatus;
import com.logic.landseaserver.models.payment.PaymentConstant.PayType;
import com.logic.landseaserver.ws.request.ReleaseRoomReq;
import com.logic.system.domain.SystemFile;
import com.logic.system.domain.User;
import com.logic.system.persistence.write.FileWriteMapper;
import com.logic.system.service.ICodeService;
import com.logic.system.service.impl.FileService;
import com.logic.system.ws.dto.FileConverter;

import net.sf.json.JSONObject;

/**
 * @Author: jack
 * @Date: 2017/6/8
 * @Description: 活动接口实现类
 */
@Service
public class DepositServiceImpl implements IDepositService
{
    
    private static final Logger LOG = LoggerFactory.getLogger(DepositServiceImpl.class);
    
    @Autowired
    private DepositReadMapper depositReadMapper;
    
    @Autowired
    private DepositWriteMapper depositWriteMapper;
    
    @Autowired
    private FileWriteMapper fileWriteMapper;
    
    @Autowired
    private DipositPDFConfiguration dipositPDFConfiguration;
    
    @Autowired
    private IProjectService projectService;
    
    @Autowired
    private IUser userService;
    
    @Autowired
    private IProjectAppartment projectAppartmentImpl;
    
    @Autowired
    private IWeBankService weBankService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    private RoomReadMapper roomReadMapper;
    
    @Autowired
    private ISendSmsService sendSmsService;
    
    @Autowired
    private ICustomer customerService;
    
    @Autowired
    private WebankParamReadMapper webankParamReadMapper;
    
    @Autowired
    private ContractReadMapper contractReadMapper;
    
    @Autowired
    private ICodeService codeService;
    
    @Autowired
    private BillIndependentService billIndependentService;
    
    @Autowired
    private IBillPaymentService billPaymentService;
    
    @Autowired
    private BillPaymentWriteMapper billPaymentWriteMapper;
    
    @Autowired
    private BalanceSheetRecordWriteMapper balanceSheetRecordWriteMapper;
    
    @Autowired
    private CouponUsedService couponUsedService;
    
    @Autowired
    private AuthCodeService authCodeService;

    @Autowired
    private UserFileWriteMapper userFileWriteMapper;

    @Autowired
    private UserFileReadMapper userFileReadMapper;

    @Autowired
    private CustomerReadMapper customerReadMapper;

    @Autowired
    private IConfigurationService configService;

    @Autowired
    private CouponWriteMapper couponWriteMapper;

    @Autowired
    private CustomerCardReadMapper customerCardReadMapper;

    @Autowired
    private CustomerCardWriteMapper customerCardWriteMapper;

    @Autowired
    private ICustomerCardService customerCardService;
    /**
     * 汉语中数字大写
     */
    private static final String[] CN_UPPER_NUMBER = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    
    /**
     * 汉语中货币单位大写，这样的设计类似于占位符
     */
    private static final String[] CN_UPPER_MONETRAY_UNIT =
        {"分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "兆", "拾", "佰", "仟"};
    
    /**
     * 特殊字符：整
     */
    private static final String CN_FULL = "整";
    
    /**
     * 特殊字符：负
     */
    private static final String CN_NEGATIVE = "负";
    
    /**
     * 金额的精度，默认值为2
     */
    private static final int MONEY_PRECISION = 2;
    
    /**
     * 特殊字符：零元整
     */
    private static final String CN_ZEOR_FULL = "零元" + CN_FULL;
    
    @Override
    public void delete(String arg0)
        throws BusinessException
    {
        
    }
    
    @Override
    public DepositDTO get(Integer arg0)
        throws BusinessException
    {
        DepositDTO depositDTO = depositReadMapper.getDepositDetail(arg0);
        depositDTO.setNowTime(new Date());
        if (depositDTO.getPdfId() != null)
        {
            depositDTO.setPdf(FileConverter.fromFileToDTO((SystemFile)this.fileService.get(depositDTO.getPdfId())));
        }
        if (depositDTO.getPdfImg() != null)
        {
            depositDTO.setImage(FileConverter.fromFileToDTO((SystemFile)this.fileService.get(depositDTO.getPdfImg())));
        }
        //查询银行卡信息
        //查询授权码使用信息
        HashMap cardMap= new HashMap();
        cardMap.put("mainId",arg0);
        cardMap.put("mainType", QueryUesdCodeType.DEPOSIT);
        depositDTO.setCustomerCardDTO(customerCardReadMapper.queryCardInfo(cardMap));

        // 查询授权码使用信息
        HashMap map = new HashMap();
        map.put("originalId", depositDTO.getId());
        List<QueryCouponUesdDTO> codes = couponUsedService.querypPersonalCouponList(map);
        depositDTO.setQueryAuthCodes(codes);
        depositDTO.setHistoryFiles(queryHistoryVersions(arg0));
        return depositDTO;
    }
    
    private void validateDeposit(DepositDTO depositDTO)
        throws LandseaBusinessException
    {
        
        if (StringUtils.isEmpty(depositDTO.getUserId()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_USERID_IS_NULL);
        }
        if (StringUtils.isEmpty(depositDTO.getCity()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_CITY_IS_NULL);
        }
        if (depositDTO.getPrjId() == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_PRJID_IS_NULL);
        }
        if (StringUtils.isEmpty(depositDTO.getDesoStyle()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_STYLE_IS_NULL);
        }
        if (depositDTO.getDepositAmount() == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_DEPOSIT_IS_NULL);
        }
        if (depositDTO.getAvailableDate() == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_VALIDDATE_IS_NULL);
        }
        if (StringUtils.isEmpty(depositDTO.getPaymentMode()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_PAYMETHOD_IS_NULL);
        }
        if (StringUtils.isEmpty(depositDTO.getLease()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_LEASE_IS_NULL);
        }
    }
    
    /**
     * [描述]：事务已添加</br>
     *
     * @param depositDTO
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {LandseaBusinessException.class,
        BusinessException.class, LandseaException.class, Exception.class})
    public int insertDeposit(DepositDTO depositDTO)
        throws BusinessException, LandseaException,Exception
    {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null || userId == -1)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        // 基础校验
        validateDeposit(depositDTO);
        // 如果从前台进入
        if (depositDTO.getFrontFlag() != null && depositDTO.getFrontFlag())
        {
            if (StringUtils.isEmpty(depositDTO.getVerifyCode()))
            {
                throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_VERFIGY_CODE_IS_NULL);
            }
            // 校验验证码
            VerificationCode verification = new VerificationCode();
            verification.setCellPhone(depositDTO.getCellPhone());
            verification.setVerificationCode(depositDTO.getVerifyCode());
            verification.setOper(SendMsgCodeEnum.deposit.getCode());
            sendSmsService.checkVerification(verification);
            
            // 推荐最优房间
            Room ro = new Room();
            ro.setPrjId(depositDTO.getPrjId());
            ro.setRoomStyle(depositDTO.getDesoStyle());
            Room room = roomReadMapper.selectAprtIdByAppend(ro);
            if (room == null)
            {
                throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_DEPOSIT_FIND_NO_ROOM);
            }
            depositDTO.setRoomId(room.getId());
            depositDTO.setUserId(SecurityUtils.getCurrentLogin().getUserId());

            depositDTO.setOriginalDeposit(depositDTO.getDepositAmount());
            //租期
            Integer month =  LeaseCodeEnum.getMonth(depositDTO.getLease());
            double discountUp = 1;
            Double rentPrice = room.getRent();
            if ( month < 6) {
                Configuration config = configService.get("SYS_LEASE_PRICE_RISE");
                if (config != null) {
                    discountUp += Double.valueOf(config.getValue());
                    rentPrice = rentPrice * discountUp;
                }
            }
            depositDTO.setOriginalAmount(rentPrice);
            depositDTO.setDiscountAmount(rentPrice);
        }
        else
        {
            if (StringUtils.isEmpty(depositDTO.getRoomId()))
            {
                throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_INSERT_ROOM_IS_NULL);
            }
            // 判断此房间是否再有效合同内
            //FIX By Junny 预定房间放开在住状态的
           /* Integer counts = contractReadMapper.queryApartContractCounts(depositDTO.getRoomId());
            if (counts >= 1)
            {
                throw new LandseaBusinessException(
                    LandseaErrorMessageEnum.CONTRACT_OFFLINE_CREATE_CONTRACT_APRT_ISRENT);
            }*/
        }
        CustomerVersion customer = customerService.getNewVersion(depositDTO.getUserId());
        if(customer==null){
            throw new LandseaBusinessException(
                    LandseaErrorMessageEnum.DEPOSIT_INSERT_USERID_IS_NULL);
        }
        String ctsversion = customer.getVersionNumber();
        // 如果从前台进入
        if (depositDTO.getFrontFlag() != null && depositDTO.getFrontFlag()) {
            //如果姓名证件号码手机号码不一致 则变更用户信息
            if(customer!=null){
                StringBuffer newUserStr =new StringBuffer();
                newUserStr.append(depositDTO.getCellPhone()).append(depositDTO.getUserName()).append(depositDTO.getCertificatesId())
                        .append(depositDTO.getCertificatesType()).append(depositDTO.getAddress()).append(depositDTO.getGender());
                StringBuffer nowUserStr =new StringBuffer();
                nowUserStr.append(customer.getPhone()).append(customer.getName()).append(customer.getCertificatesNo()).
                        append(customer.getCertificatesType()).append(customer.getCertificatesAddress()).append(customer.getGender());
                if(!newUserStr.toString().equals(nowUserStr.toString())){
                    updateUserInfo(depositDTO);
                    ctsversion = VariableChar.DIR+(Integer.parseInt(ctsversion.replace(VariableChar.DIR,""))+1);
                }
            }else{
                updateUserInfo(depositDTO);
                ctsversion = VariableChar.DIR+(Integer.parseInt(ctsversion.replace(VariableChar.DIR,""))+1);
            }
        }
        //String version = checkUserInfo(depositDTO);
        int activityInt = 0;// 唯一性验证
        Deposit deposit = DepositDTO.convertToDeposit(depositDTO);
     //   deposit.setUserId(signUserId);
        
        // 判断是否使用授权码
        if (depositDTO.getAuthCodes() != null)
        {
            // check 数量是否正常
            couponUsedService.checkUesdAuthCode(QueryUesdCodeType.DEPOSIT,
                    depositDTO.getUserId(),
                depositDTO.getAuthCodes());
        }
        deposit.setUserVersion(ctsversion);
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        deposit.setCreatedBy(SecurityUtils.getCurrentLogin().getUserId());
        
        depositWriteMapper.insertSelective(deposit);
        Integer depositId = deposit.getId();
        //新增卡信息
        if(!StringUtils.isEmpty(depositDTO.getCardAccount()) && !StringUtils.isEmpty(depositDTO.getCardNo())){
            CustomerCard customerCard =depositDTO.convertDTOtoCustomerCard(depositDTO);
            customerCard.setSourceId(depositId);
            customerCard.updateCommonInfo(userId);
            customerCardWriteMapper.insertSelective(customerCard);
        }
        
        // 判断是否使用授权码
        boolean isUseCoupon = false;
        if (depositDTO.getAuthCodes() != null)
        {
            AddCouponUesd couponUesds = new AddCouponUesd();
            couponUesds.setAuthCodes(depositDTO.getAuthCodes());
            couponUesds.setMainType(LandeaConstants.QueryUesdCodeType.DEPOSIT);
            couponUesds.setMainId(depositId);
            couponUesds.setPrjId(depositDTO.getPrjId());
            couponUesds.setRoomId(depositDTO.getRoomId());
            couponUesds.setUserId(userId);
            couponUsedService.insertUesdList(couponUesds);
            isUseCoupon = true;
        }
        
        // 备份到balace_sheet中的数据
        BalanceSheetRecord depositRecord = new BalanceSheetRecord();
        depositRecord.setBillId(depositId);
        depositRecord.setProjectId(depositDTO.getPrjId());
        depositRecord.setRoomId(depositDTO.getRoomId());
        depositRecord.setBillType(BillType.RESERVE_BILL);
        depositRecord.setProjectId(depositDTO.getPrjId());
        depositRecord.setRoomId(depositDTO.getRoomId());
        // 预定合同ID就是自己的ID
        depositRecord.setContractId(depositId);
        Room room1 = roomReadMapper.selectByPrimaryKey(depositDTO.getRoomId());
        depositRecord.setHouseNum(room1.getHouseNum());
        
        depositRecord.setStartTime(new Date());
        depositRecord.setEndTime(depositDTO.getAvailableDate());
        depositRecord.setReceivableMoney(depositDTO.getDepositAmount());
        depositRecord.setBillStatus(BillStatusEnum.BIST3.getCode());
        depositRecord.setExpenditureCode(BillTypeEnum.CTBI18.getCode());
        if (isUseCoupon)
        {
            // 如果使用授权码，则入授权码
            depositRecord.setExpenditure(BillTypeEnum.CTBI18.getName());
            depositRecord.setProduceType(ProduceType.AUTHCODE);
        }
        else
        {
            depositRecord.setExpenditure(BillTypeEnum.CTBI18.getName());
            depositRecord.setProduceType(ProduceType.PAY);
        }
        billIndependentService.insertBalanceSheet(depositRecord);
        //如果存在在住合同，则不需修改房态图信息
        Integer counts = contractReadMapper.queryApartContractCounts(depositDTO.getRoomId());
        if (counts<1) {
            Room room = new Room();
            room.setId(depositDTO.getRoomId());
            room.setAppendStatus("LRB2");
            projectAppartmentImpl.updateAppendStatus(room);
        }
        
        DepositPdfDTO pdfDto = DepositDTO.convertToDepositPdfDTO(depositDTO);
        pdfDto.setCertificatesTypeCH(codeService.getCode(depositDTO.getCertificatesType()).getCodeDescZh());
        pdfDto.setProject(depositReadMapper.selectProject(depositDTO.getPrjId()));
        pdfDto.setRoom(depositReadMapper.selectRoomDTO(depositDTO.getRoomId()));
        pdfDto.setAddress(depositReadMapper.selectAddressDTO(depositDTO.getPrjId()));
        pdfDto.setPaymentModeName(codeService.getCode(depositDTO.getPaymentMode()).getCodeDescZh());
        pdfDto.setLeaseCH(codeService.getCode(depositDTO.getLease()).getCodeDescZh());
        pdfDto.setChapter(false);
        pdfDto.setId(deposit.getId());
        pdfDto.setCustomerCardDTO(DepositDTO.convertToCustomerCardDto(depositDTO));
        createOrUpdatePDF(pdfDto);
        return deposit.getId();
    }
    private void updateUserInfo(DepositDTO req)
            throws Exception {
        Customer customer = customerReadMapper.selectByUserId(req.getUserId());
        if(customer!=null){
            CustomerDTO customerDTO = new CustomerDTO();
            customerDTO.setId(customer.getId());
            customerDTO.setUserId(req.getUserId());
            customerDTO.setName(req.getUserName());
            customerDTO.setPhone(req.getCellPhone());
            customerDTO.setCertificatesType(req.getCertificatesType());
            customerDTO.setCertificatesNo(req.getCertificatesId());
            customerDTO.setCertificatesAddress(req.getAddress());
            customerDTO.setGender(req.getGender());
            customerService.updateCustomer(customerDTO);
        }
    }
    private void createOrUpdatePDF(DepositPdfDTO deposit)
        throws LandseaException
    {
        // 生成PDF文件
        try
        {
            deposit.setOprType(LandeaConstants.PdfOprType.ADD_UPDATE);
            // 生成PDF文件
            Integer pdfId = this.productDipositPdf(deposit);
            if (pdfId != null)
            {
                deposit.setPdfId(pdfId);
                // 生成PDF图片
                this.createOrUpdateImg(deposit, pdfId);
            }
        }
        catch (Exception e)
        {
            LOG.info("createOrUpdatePDF error:", e);
            throw LandseaException.createException(LandseaErrorMessageEnum.DEPOSIT_PDF_NOT_EXISTS_NULL, e);
        }
    }
    
    private String checkUserInfo(DepositDTO dto)
        throws LandseaBusinessException
    {
        CustomerVersion customer = customerService.getNewVersion(dto.getUserId());
        /*if (!dto.getCellPhone().equals(customer.getPhone()))
        {
            throw new LandseaBusinessException(
                String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(), VariableChar.PHONE));
        }
        
        if (!dto.getUserName().equals(customer.getName()))
        {
            throw new LandseaBusinessException(
                String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(), VariableChar.NAME));
        }
        
        if (!dto.getGender().equals(customer.getGender()))
        {
            throw new LandseaBusinessException(
                String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(), VariableChar.GENDER));
        }
        if (!dto.getCertificatesType().equals(customer.getCertificatesType()))
        {
            throw new LandseaBusinessException(
                String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(), VariableChar.CERTIFICATESTYPE));
        }
        if (!dto.getCertificatesType().equals(customer.getCertificatesType()))
        {
            throw new LandseaBusinessException(
                String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(), VariableChar.CERTIFICATESNO));
        }
        if (!dto.getAddress().equals(customer.getCertificatesAddress()))
        {
            throw new LandseaBusinessException(String.format(LandseaErrorMessageEnum.DEPOSIT_PARAM_IS_ERROR.getDesc(),
                VariableChar.CERTIFICATESADDRESS));
        }*/
        
        return customer.getVersionNumber();
        
    }
    
    @Override
    public void editDeposit(DepositDTO depositDTO)
        throws BusinessException, LandseaException
    {
        Deposit deposit = depositReadMapper.selectByPrimaryKey(depositDTO.getId());
        boolean chapterFlag = deposit.getChapter();
        if (deposit == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_UPDATE_VALIDID_IS_NULL);
        }
        // 判断房间是否有更换
        Integer newRoomId = depositDTO.getRoomId();
        Integer oldRoomId = deposit.getRoomId();
        if (!newRoomId.equals(oldRoomId))
        {
            // 将原有房间状态改为空置，将目前预定房间状态改为预定
            //查询当前房间是否有已签约的合同
            Integer counts = contractReadMapper.queryApartContractCounts(oldRoomId);
            if (counts == 0 ) {
                Room oldRoom = new Room();
                oldRoom.setId(oldRoomId);
                oldRoom.setAppendStatus("LRB1");
                projectAppartmentImpl.updateAppendStatus(oldRoom);
            }
            Room nowRoom = new Room();
            nowRoom.setId(newRoomId);
            nowRoom.setAppendStatus("LRB2");
            projectAppartmentImpl.updateAppendStatus(nowRoom);
        }
        // 编辑操作
        if (StringUtils.isEmpty(depositDTO.getImageId()))
        {
            deposit = DepositDTO.convertToDeposit(depositDTO);
            // 生成PDF
            //DepositPdfDTO pdfDto = DepositPdfDTO.convertToDepositPdfDTO(deposit);
            //Updated by Daniel for 预定信息
            DepositPdfDTO pdfDto = DepositDTO.convertToDepositPdfDTO(depositDTO);
            pdfDto.setChapter(chapterFlag);
            pdfDto.setCertificatesTypeCH(codeService.getCode(depositDTO.getCertificatesType()).getCodeDescZh());
            pdfDto.setProject(depositReadMapper.selectProject(depositDTO.getPrjId()));
            pdfDto.setRoom(depositReadMapper.selectRoomDTO(depositDTO.getRoomId()));
            pdfDto.setAddress(depositReadMapper.selectAddressDTO(depositDTO.getPrjId()));
            pdfDto.setPaymentModeName(codeService.getCode(depositDTO.getPaymentMode()).getCodeDescZh());
            pdfDto.setLeaseCH(codeService.getCode(depositDTO.getLease()).getCodeDescZh());
            pdfDto.setCustomerCardDTO( DepositDTO.convertToCustomerCardDto(depositDTO));
            createOrUpdatePDF(pdfDto);
        }
        else
        {// 如果是支付时上传凭证 POS支付处理 =->TOOD by Junny 1013已新增posCallBack处理
            /*
             * deposit.setImageId(depositDTO.getImageId() == null ? null : depositDTO.getImageId());
             * deposit.setPayMethod(depositDTO.getPayMethod() == null ? null : depositDTO.getPayMethod());
             * deposit.setDepositAmount(depositDTO.getDepositAmount() == null ? null : depositDTO.getDepositAmount());
             * deposit.setPaySn(depositDTO.getPaySn() == null ? null : depositDTO.getPaySn());
             */
        }
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
    }
    
    /**
     * pos支付成功之后处理逻辑
     * 
     * @throws LandseaException
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {LandseaException.class, BusinessException.class,
        Exception.class})
    public void updateDepostiId(Integer depostiId)
        throws BusinessException, LandseaException
    {
        Deposit deposit = depositReadMapper.selectByPrimaryKey(depostiId);
        // 生成预定编号
        ProjectDetailDTO prj = projectService.getProjectDetail(deposit.getPrjId());
        String depositSn =
            prj.getPrjCode() + new DecimalFormat("000000").format(depositReadMapper.getMaxContractCode());
        deposit.setDepositSn(depositSn);
        deposit.setStatus("_DS2");
        // 生成支付时间
        Date payTime = new Date();
        deposit.setPayDate(payTime);
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
        
        // 入库payment表,直接新增
        BillPaymentDTO billPaymentDTO = new BillPaymentDTO();
        billPaymentDTO.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        billPaymentDTO.setBank("POS");
        billPaymentDTO.setBillId(depostiId);
        billPaymentDTO.setMoney(deposit.getDepositAmount());
        billPaymentDTO.setPayType(PayType.POS);
        billPaymentDTO.setStatus(BillPaymentStatus.SUCCESS); // 未支付
        billPaymentDTO.setBillType(BillType.RESERVE_BILL);
        billPaymentDTO.setOrderNo(depositSn);
        billPaymentDTO.setTransactionNo(depositSn);
        billPaymentDTO.setTime(payTime);
        billPaymentService.insertBillPaymentDTO(billPaymentDTO);
        
        // pos里面处理预定的往balancedSheet修改状态
        billIndependentService.depUpdateBalanceSheet(depostiId, depositSn, payTime);
        
        // 更新授权码为已使用状态
        authCodeService.updateCouponStatusAfterPay(QueryUesdCodeType.DEPOSIT, depostiId);
        
        // 修改PDF name 和 pdf imgName
        // systemFile 修改文件名 已经重命名服务器上的文件名
        renamePDF(deposit);
    }
    
    @Override
    public void renamePDF(Deposit deposit)
        throws BusinessException
    {
        if(StringUtils.isEmpty(deposit.getDepositSn())){
            deposit = depositReadMapper.selectByPrimaryKey(deposit.getId());
        }
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        String fileName = deposit.getDepositSn()+"01";

        HashMap queryMap = new HashMap();
        queryMap.put("path",dipositPDFConfiguration.getDipositPath());
        queryMap.put("fileType","pdf");
        queryMap.put("name", deposit.getDepositSn());
        List<SystemFile> systemFiles = fileService.getFilesByMap(queryMap);
        if(systemFiles.size()>0){
            fileName =deposit.getDepositSn()+String.format("%02d", systemFiles.size()+1);
        }
        if (deposit.getPdfId() != null)
        {
            SystemFile localPdfFile = (SystemFile)fileService.get(deposit.getPdfId() + "");
            String pdfName = fileName + ".pdf";
            FileTool.reName(localPdfFile.getLocalFullPath(), pdfName);
            SystemFile pdfFile = new SystemFile();
            pdfFile.setId(deposit.getPdfId());
            pdfFile.setName(pdfName);
            pdfFile.updateCommonInfo(userId);
            fileWriteMapper.updateByPrimaryKeySelective(pdfFile);
        }
        if (deposit.getPdfImg() != null)
        {
            SystemFile localPdfImgFile = (SystemFile)fileService.get(deposit.getPdfImg() + "");
            String imgName = fileName + ".jpg";
            FileTool.reName(localPdfImgFile.getLocalFullPath(), imgName);
            SystemFile imgFile = new SystemFile();
            imgFile.setId(deposit.getPdfImg());
            imgFile.setName(imgName);
            imgFile.updateCommonInfo(userId);
            fileWriteMapper.updateByPrimaryKeySelective(imgFile);
        }
    }
    
    @Override
    public void deleteDeposit(Integer id)
        throws BusinessException
    {
        Deposit depositPre = depositReadMapper.selectByPrimaryKey(id);
        Deposit deposit = new Deposit();
        deposit.setId(id);
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
        deposit.setDeleted(true);
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
        // balance_sheet表删除失效的预定合同
        // 因为预定合同的id就是预定自己的id
        deleteBalanceByDepositId(id);
        // 释放房源 added by Daniel on 20170620
        // p4需求不改房源
        Room room = new Room();
        room.setId(depositPre.getRoomId());
        room.setAppendStatus("LRB1");// 空置
        projectAppartmentImpl.updateAppendStatus(room);
        LOG.info("delete deposit:" + deposit.getId());
        // 删除授权码使用记录
        couponUsedService.deleteCouponUesd(id, LandeaConstants.QueryUesdCodeType.DEPOSIT);
        
    }
    
    private void deleteBalanceByDepositId(Integer id)
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("lastModifiedBy", SecurityUtils.getCurrentLogin().getUserId());
        map.put("lastModifiedDtm", new Date());
        map.put("contractId", id);
        balanceSheetRecordWriteMapper.deleteDeposit(map);
    }
    
    @Override
    public List<DepositDTO> query(QueryUtil queryUtil)
    {
        List<DepositDTO> result = depositReadMapper.getDepositDTOList(queryUtil);
        for (int i = 0; i < result.size(); i++)
        {
            String namePhone = "";
            DepositDTO de = result.get(i);
//            String phone = de.getCellPhone();
//            String name = de.getUserName();
//            namePhone = name + " | " + phone;
//            de.setNameAndPhone(namePhone);
            
            // 房间风格|房间号
            String roomNo = de.getRoomNo();
            String styleName = de.getDesoStyleName();
            String desoStyleNameRoomNo = styleName + " | " + roomNo;
            de.setDesoStyleNameRoomNo(desoStyleNameRoomNo);
            
            SystemFile img = null;
            try
            {
                if (!"".equals(de.getPdfId()) && null != de.getPdfId())
                {
                    img = (SystemFile)fileService.get(de.getPdfId());
                    if (null != img)
                    {
                        de.setImagePath(img.getFullPath());
                    }
                }
            }
            catch (BusinessException e)
            {
                LOG.error("query error", e);
            }
            
            // Added by Daniel for 凭证路径 on 20170623
            if (!StringUtils.isEmpty(de.getImageId()))
            {
                de.setImageId(fileService.getRemoteFullPath(de.getImageId()));
            }
            // result.add(de);
        }
        return result;
    }
    
    @Override
    public void update(Object obj)
        throws BusinessException
    {
        Deposit deposit = (Deposit)obj;
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
    }
    
    @Override
    public Boolean validate(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public Boolean validateForDelete(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public Boolean validateForUpdate(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public int insert(Object arg0)
        throws BusinessException
    {
        return 0;
    }
    
    @Override
    public Boolean validateForInsert(Object arg0)
        throws BusinessException
    {
        return null;
    }
    
    @Override
    public DepositPdfDTO getPdfDitail(Integer depositId)
    {
        HashMap map = new HashMap();
        map.put("depositId",depositId);
        DepositPdfDTO dto = depositReadMapper.getDipositPdfDTO(map);
        return dto;
    }
    
    @Override
    public Integer productDipositPdf(DepositPdfDTO dto)
        throws Exception
    {
        /*
         * if (!StringUtils.isEmpty(dto.getId())){ dto = depositReadMapper.getDipositPdfDTO(dto.getId()); }
         */
        if (dto.getChapter())
        {
            // 已经进行电子签，不再进行预定合同的编辑
            return null;
        }
        Map<String, String> data = new HashMap<String, String>();
        data.put("dId", dto.getId() == null ? "" : dto.getId().toString());
        data.put("depositSN", dto.getDepositSn() == null ? "" : dto.getDepositSn());
        String contractName = dto.getProject().getContractName() == null ? "" : dto.getProject().getContractName();
        data.put("jiafangName", contractName);
        data.put("jiafangName1", contractName + "预定协议");
        data.put("yifangName", dto.getUserName() == null ? "" : dto.getUserName());
        data.put("userTel", dto.getCellPhone() == null ? "" : dto.getCellPhone());
        data.put("IdType", dto.getCertificatesTypeCH() == null ? "" : dto.getCertificatesTypeCH());
        data.put("IdCode", dto.getCertificatesId() == null ? "" : dto.getCertificatesId());
        data.put("prjName", dto.getProject().getPrjName() == null ? "" : dto.getProject().getPrjName());
        data.put("roomNum", dto.getRoom().getHouseNum() == null ? "" : dto.getRoom().getHouseNum());
        String province = dto.getAddress().getProvince();
        // 傻瓜式处理下直辖市 added by Daniel on 20170625
        if ("北京".equalsIgnoreCase(province) || "天津".equalsIgnoreCase(province) || "重庆".equalsIgnoreCase(province)
            || "上海".equalsIgnoreCase(province))
        {
            province = "";
        }
        
        String city = dto.getAddress().getCity();
        String area = dto.getAddress().getCounty();
        
       // DecimalFormat df = new DecimalFormat("0.00");
        DecimalFormat df = new DecimalFormat("##0");
        data.put("address", province + city + area + dto.getAddress().getAddressLine1());
        data.put("diposit", dto.getDepositAmount() == null ? "" : df.format(dto.getDepositAmount()) + "");
        data.put("dipositCH",
            dto.getDepositAmount() == null ? "" : number2CNMontrayUnit(new BigDecimal(dto.getDepositAmount())));
        
        Date availableDate = dto.getAvailableDate();
        Calendar calin = Calendar.getInstance();
        calin.setTime(availableDate);
        
        data.put("signYear", calin.get(Calendar.YEAR) + "");
        data.put("signMonth", (calin.get(Calendar.MONTH) + 1) + "");
        data.put("signDay", calin.get(Calendar.DAY_OF_MONTH) + "");
        data.put("prjName2", dto.getProject().getPrjName());
        
        String leaseCH = dto.getLeaseCH();
        data.put("rentLong", leaseCH == null ? "" : leaseCH.substring(0, leaseCH.indexOf("个")));
        
        data.put("rentType", dto.getPaymentModeName());
        
        /*
         * Double rent = dto.getRoom().getRent(); Configuration config =
         * configService.get(SystemCodeEnum.SYS_LEASE_PRICE_RISE.getCode()); Assert.hasText(rent.toString(), "没有租金！");
         * Double leaseRise = Double.parseDouble(config.getValue()); if
         * (SystemCodeEnum.LEASE_ONE_MONTH.getCode().equals(dto.getLease()) ||
         * SystemCodeEnum.LEASE_THREE_MONTH.getCode().equals(dto.getLease())) { rent = rent * (leaseRise + 1); }
         */
        
        HashMap<String, PaymentModelCodeEnum> yayiMap = new HashMap<String, PaymentModelCodeEnum>();
        yayiMap.put(PaymentModelCodeEnum.PAMO8.getCode(), PaymentModelCodeEnum.PAMO8);
        yayiMap.put(PaymentModelCodeEnum.PAMO5.getCode(), PaymentModelCodeEnum.PAMO5);
        yayiMap.put(PaymentModelCodeEnum.PAMO6.getCode(), PaymentModelCodeEnum.PAMO6);
        yayiMap.put(PaymentModelCodeEnum.PAMO7.getCode(), PaymentModelCodeEnum.PAMO7);
        
        HashMap<String, PaymentModelCodeEnum> yaerMap = new HashMap<String, PaymentModelCodeEnum>();
        yaerMap.put(PaymentModelCodeEnum.PAMO1.getCode(), PaymentModelCodeEnum.PAMO1);
        yaerMap.put(PaymentModelCodeEnum.PAMO3.getCode(), PaymentModelCodeEnum.PAMO3);
        yaerMap.put(PaymentModelCodeEnum.PAMO9.getCode(), PaymentModelCodeEnum.PAMO9);
        
        // 计算房租金额
        Double rent = dto.getDiscountAmount();
        // Double rent = LandSeaUtil.get2Double(dto.getOriginalAmount() - dto.getDiscountAmount());
        String yajinType = dto.getPaymentMode();
        Double diposit2 = null;
        if (yayiMap.containsKey(yajinType))
        {
            diposit2 = rent;
        }
        else if (yaerMap.containsKey(yajinType))
        {
            diposit2 = rent * 2;
        }
        // rent = LandSeaUtil.get2Double(rent - dto.getDiscountAmount());
        data.put("rent", dto.getRoom().getRent() == null ? "0" : df.format(rent) + "");
        data.put("propertyFee",
            dto.getRoom().getPropertyFee() == null ? "0" : df.format(dto.getRoom().getPropertyFee()));
        data.put("diposit2", diposit2 == null ? "" : df.format(diposit2));
        data.put("waterDiposit",
            dto.getProject().getDepositWater() == null ? "0" : df.format(dto.getProject().getDepositWater()));// 水押金默认为0
        data.put("jiaN", dto.getProject().getContractName());
        data.put("jiaTell", dto.getProject().getContractPhone());
        SimpleDateFormat ymdFormatter = new SimpleDateFormat("yyyy-MM-dd");
        // 地址不正确问题修改 Daniel
        data.put("jiaAddress", dto.getProject().getContractAddress());
        // data.put("jiaAddress", "");
        Date crDtm = dto.getCreatedDtm() == null ? new Date() : dto.getCreatedDtm();
        data.put("jiaDate", ymdFormatter.format(crDtm));
        // data.put("yiN", dto.getUserName());
        data.put("yiTell", dto.getCellPhone());
        data.put("yiAddress", dto.getCustomerAddress());
        data.put("yiDate", ymdFormatter.format(crDtm));
        if(dto.getOprType().equals(LandeaConstants.PdfOprType.CHANGE)){
            //获取上一个版本的生成日期
            SystemFile sf  = (SystemFile) fileService.get(dto.getPdfId());
            if(sf!=null){
                String lastFileAddDate = DateUtil.getInstence().convertDate(sf.getCreatedDtm());
                if(!StringUtils.isEmpty(lastFileAddDate)){
                    data.put("oy",lastFileAddDate.substring(0, 4));
                    data.put("om",lastFileAddDate.substring(5, 7));
                    data.put("od",lastFileAddDate.substring(8, 10));
                }
            }
        }

        data.put("depositStatus",dto.getStatus());
        if(dto.getCustomerCardDTO()!=null){
            data.put("cardAccount",dto.getCustomerCardDTO().getCardAccount()==null ? "":dto.getCustomerCardDTO().getCardAccount());
            data.put("cardUserName",dto.getCustomerCardDTO().getCardUserName()==null ? "":dto.getCustomerCardDTO().getCardUserName());
            data.put("cardCellPhone",dto.getCustomerCardDTO().getCellPhone()==null ? "":dto.getCustomerCardDTO().getCellPhone());
            data.put("bankName",dto.getCustomerCardDTO().getBankName()==null ? "":dto.getCustomerCardDTO().getBankName());
            data.put("bankBrname",dto.getCustomerCardDTO().getBankBrname()==null ? "":dto.getCustomerCardDTO().getBankBrname());
            data.put("cardNo",dto.getCustomerCardDTO().getCardNo()==null ? "":dto.getCustomerCardDTO().getCardNo());
        }

        Integer result = producePDF(data, dto);
        return result;
    }
    
    public Integer producePDF(Map<String, String> data, DepositPdfDTO dto)
        throws Exception
    {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        Integer fileId = null;
        try
        {
            PdfReader reader = null;
            String depositStatus = (String)data.get("depositStatus");
            if(dto.getOprType().equals(LandeaConstants.PdfOprType.CHANGE) && !depositStatus.equals(DepositEnum._DS1.getCode())){
                reader = new PdfReader(ContractServiceImpl.class.getClassLoader().getResource("dipositPdfV.pdf"));
            }else{
                reader = new PdfReader(ContractServiceImpl.class.getClassLoader().getResource("dipositPdf.pdf"));
            }
             bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            PdfContentByte under = ps.getUnderContent(7);
            /* 使用中文字体 */
            BaseFont bf =
                BaseFont.createFont(ContractServiceImpl.class.getClassLoader().getResource("STSONG.TTF").toString(),
                    BaseFont.IDENTITY_H,
                    BaseFont.NOT_EMBEDDED);
            Font font = FontFactory.getFont(FontFactory.HELVETICA, 16, Font.BOLD);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            
            fillData(fields, data);
            
            ps.setFormFlattening(true);
            ps.close();
            String filepath = dipositPDFConfiguration.getLocal() + "/" + dipositPDFConfiguration.getDipositPath();
            File file = new File(filepath);
            // 如果文件夹不存在则创建
            if (!file.exists() && !file.isDirectory())
            {
                file.mkdir();
            }
            Date nowTime = new Date(System.currentTimeMillis());
            SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String time = sdFormatter.format(nowTime);
            // String filename = filepath + "/" + data.get("depositSN") + "_" + time + ".pdf";
            String filename = filepath + "/" + data.get("dId") + "_" + time + ".pdf";
            fos = new FileOutputStream(filename);
            fos.write(bos.toByteArray());
            
            // 将url插入数据库
            SystemFile systemFile = new SystemFile();
            String fileName = data.get("dId") + "_" + time + ".pdf";
            int size = bos.size() / 1024;
            systemFile.setFileSize(size);
            systemFile.setPath(dipositPDFConfiguration.getDipositPath());
            systemFile.setFileType("pdf");
            systemFile.setName(fileName);
            systemFile.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
            String localPath =
                dipositPDFConfiguration.getLocal() + "/" + dipositPDFConfiguration.getDipositPath() + "/" + fileName;
            // 如果是未生成过pdf、租客信息变更 则新增pdf
            if (dto.getPdfId() == null || dto.getOprType().equals(LandeaConstants.PdfOprType.CHANGE))
            {
                fileWriteMapper.insertSelective(systemFile);
                fileId = systemFile.getId();
            }
            else
            {
                systemFile.setId(dto.getPdfId());
                // 生成过PDF 则将之前的PDF删除，再修改当前记录
                SystemFile pdfFile = (SystemFile)fileService.get(dto.getPdfId() + "");
                localPath = pdfFile.getLocalFullPath();
                fileService.deleteFile(localPath);
                fileWriteMapper.updateByPrimaryKeySelective(systemFile);
            }
            // createOrUpdateImg(dto, localPath, fileId);
            
        }
        catch (Exception e)
        {
            LOG.error("producePDF Exception:", e);
            throw e;
        }
        finally
        {
            fos.flush();
            fos.close();
            bos.close();
        }
        return fileId;
    }
    
    // private void createOrUpdateImg(DepositPdfDTO dto, String pdfLocalPath, Integer pdfFileId) {
    private void createOrUpdateImg(DepositPdfDTO dto, Integer pdfFileId)
        throws BusinessException
    {
        // 获取pdf的localpath
        FileDTO fileDTO = FileConverter.fromFileToDTO((SystemFile)this.fileService.get(pdfFileId));
        LOG.info("fileDTO is:" + fileDTO);
        if (fileDTO != null)
        {
            // 不存在 属于新增
            String fileName = fileDTO.getName().replace(".pdf", ".jpg");
            LOG.info("file fileName is:" + fileName);
            try
            {
                String imageLocalFullPath = dipositPDFConfiguration.getLocal() + "/"
                    + dipositPDFConfiguration.getDipositPath() + "/" + fileName;
                LOG.info("imageLocalFullPath:" + imageLocalFullPath);
                PDF2Image.createImg(fileDTO.getLocalFullPath(), imageLocalFullPath);
                // 保存水印图片到数据库
                SystemFile imgFile = new SystemFile();
                imgFile.setName(fileName);
                imgFile.setPath(dipositPDFConfiguration.getDipositPath());
                imgFile.setFileType("jpg");
                if (dto.getPdfImg() == null || dto.getOprType().equals(LandeaConstants.PdfOprType.CHANGE))
                {
                    fileService.insert(imgFile);
                }
                else
                {
                    imgFile.setId(dto.getPdfImg());
                    // 生成过img 则将之前的img删除，再修改当前记录
                    SystemFile pdfFile = (SystemFile)fileService.get(dto.getPdfImg() + "");
                    String oldLocalPath = pdfFile.getLocalFullPath();
                    fileService.deleteFile(oldLocalPath);
                    fileWriteMapper.updateByPrimaryKeySelective(imgFile);
                }
                Deposit deposit = new Deposit();
                if (pdfFileId != null)
                {
                    deposit.setPdfId(pdfFileId);
                }
                deposit.setId(dto.getId());
                deposit.setPdfImg(imgFile.getId());
                deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                // deposit.setCreatedBy(SecurityUtils.getCurrentLogin().getUserId());
                depositWriteMapper.updateByPrimaryKeySelective(deposit);
            }
            catch (BusinessException be)
            {
                LOG.error("create or update pdf img BusinessException:" + be.getMessage());
            }
            catch (IOException e)
            {
                LOG.error("create or update pdf img IOException:", e);
            }
        }
    }
    
    public static void fillData(AcroFields fields, Map<String, String> data)
        throws IOException, DocumentException
    {
        for (String key : data.keySet())
        {
            String value = data.get(key);
            fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
        }
    }
    
    /**
     * 把输入的金额转换为汉语中人民币的大写
     *
     * @param numberOfMoney 输入的金额
     * @return 对应的汉语大写
     */
    public static String number2CNMontrayUnit(BigDecimal numberOfMoney)
    {
        StringBuffer sb = new StringBuffer();
        // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or
        // positive.
        int signum = numberOfMoney.signum();
        // 零元整的情况
        if (signum == 0)
        {
            return CN_ZEOR_FULL;
        }
        // 这里会进行金额的四舍五入
        long number = numberOfMoney.movePointRight(MONEY_PRECISION).setScale(0, 4).abs().longValue();
        // 得到小数点后两位值
        long scale = number % 100;
        int numUnit = 0;
        int numIndex = 0;
        boolean getZero = false;
        // 判断最后两位数，一共有四中情况：00 = 0, 01 = 1, 10, 11
        if (!(scale > 0))
        {
            numIndex = 2;
            number = number / 100;
            getZero = true;
        }
        if ((scale > 0) && (!(scale % 10 > 0)))
        {
            numIndex = 1;
            number = number / 10;
            getZero = true;
        }
        int zeroSize = 0;
        while (true)
        {
            if (number <= 0)
            {
                break;
            }
            // 每次获取到最后一个数
            numUnit = (int)(number % 10);
            if (numUnit > 0)
            {
                if ((numIndex == 9) && (zeroSize >= 3))
                {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]);
                }
                if ((numIndex == 13) && (zeroSize >= 3))
                {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]);
                }
                sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                getZero = false;
                zeroSize = 0;
            }
            else
            {
                ++zeroSize;
                if (!(getZero))
                {
                    sb.insert(0, CN_UPPER_NUMBER[numUnit]);
                }
                if (numIndex == 2)
                {
                    if (number > 0)
                    {
                        sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                    }
                }
                else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0))
                {
                    sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]);
                }
                getZero = true;
            }
            // 让number每次都去掉最后一个数
            number = number / 10;
            ++numIndex;
        }
        // 如果signum == -1，则说明输入的数字为负数，就在最前面追加特殊字符：负
        if (signum == -1)
        {
            sb.insert(0, CN_NEGATIVE);
        }
        // 输入的数字小数点后两位为"00"的情况，则要在最后追加特殊字符：整
        if (!(scale > 0))
        {
            sb.append(CN_FULL);
        }
        return sb.toString();
    }
    
    /*
     * private Integer checkUserCellPhone(DepositDTO req) throws BusinessException { // 判断是否存在登录账号 User pUser = new
     * User(); pUser.setLoginId(req.getCellPhone()); User existUser = userService.itExistUser(pUser);
     * 
     * UserDTO userDTO = new UserDTO();
     * 
     * userDTO.setLoginId(req.getCellPhone()); CustomerDTO customerDTO = new CustomerDTO();
     * customerDTO.setName(req.getUserName()); customerDTO.setPhone(req.getCellPhone());
     * customerDTO.setCertificatesType(req.getCertificatesType());
     * customerDTO.setCertificatesNo(req.getCertificatesId()); customerDTO.setGender(req.getGender());
     * userDTO.setCustomerDTO(customerDTO); if (existUser != null) { userDTO.setId(existUser.getId());
     * userService.update(userDTO); } else {
     * userDTO.setPassword(SysUtil.MD5Digest(userDTO.getLoginId().substring(userDTO.getLoginId().length() - 6)));
     * Integer userId = userService.insert(userDTO); userDTO.setId(userId); }
     * 
     * return userDTO.getId(); }
     */
    
    @Override
    public void cancleComeDueDeposit(String comeDueDate)
    {
        
        LOG.info("cancleComeDueDeposit is ：" + comeDueDate);
        Map<String, String> params = new HashMap<>();
        params.put("status", DepositEnum._DS2.getCode());
        params.put("availableDate", comeDueDate);
        List<Deposit> dsList = depositReadMapper.queryComeDueDeposit(params);
        for (Deposit deposit : dsList)
        {
            LOG.info("deposit {} is 过期,userid is {}", deposit.getId(), deposit.getUserId());
            try
            {
                // 修改预定状态位已过期
                depositWriteMapper.updateComeDueDeposit(deposit.getId());
                
                /*
                 * P4 过期不改变房间状态 Room room = new Room(); room.setId(deposit.getRoomId()); room.setAppendStatus("LRB1");//
                 * 空置 projectAppartmentImpl.updateAppendStatus(room);
                 */
            }
            catch (Exception e)
            {
                LOG.error("deposit {} is comedue,userID is {},release room is BusinessException ",
                    deposit.getId(),
                    deposit.getUserId());
                LOG.error(e.getMessage());
            }
        }
    }
    
    // 微众支付
    @Override
    public WeBankPayRespDTO getDepositWeBankPay(DepositWeBankPayReqDTO depositWeBankPayReqDTO)
        throws LandseaException, Exception
    {
        
        Assert.hasText(depositWeBankPayReqDTO.getDepositId(), "没有预定Id");
        
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String reqTime = sdFormatter.format(nowTime);
        
        // 验证
        DepositDTO depositDTO =
            depositReadMapper.getDepositDetail(Integer.parseInt(depositWeBankPayReqDTO.getDepositId()));
        if (depositDTO == null)
        {
            throw new Exception("未查询到订单信息，或该订单已删除！");
        }
        if (!"_DS1".equals(depositDTO.getStatus()))
        {
            throw new Exception("预定状态非\"草稿\"状态");
        }
        
        WebankParam webankParam = webankParamReadMapper.selectByPrjId(depositDTO.getPrjId());
        
        String payType = depositWeBankPayReqDTO.getPayType();
        
        WeBankPayDTO payinfo = new WeBankPayDTO();
        
        payinfo.setGoodsName(depositDTO.getPrjName() + depositDTO.getRoomNo() + "号房间订单");
        payinfo.setPrice(depositDTO.getDepositAmount() + "");
        payinfo.setBusinessType("E1");
        if (PayType.WEBANK_MOBILE.equals(payType))
        { // 收银台
            if (depositDTO.getUserId() == null)
            {
                throw new BusinessException("没有userID");
            }
            payinfo.setUserId(depositDTO.getUserId());
        }
        WeBankPayRespDTO paydto = null;
        
        String bankCode = "";
        // 支付方式(网页)：微众-支付宝
        if (PaymentConstant.PayType.WEBANK_ALIPAY.equals(payType))
        {
            bankCode = "微众银行收单";
        }
        // 支付方式(网页)：微众-微信
        else if (PaymentConstant.PayType.WEBANK_WECHAT.equals(payType))
        {
            bankCode = "微众银行收单";
        }
        // 支付方式(网页)：微众-收银台
        else if (PaymentConstant.PayType.WEBANK_MOBILE.equals(payType))
        {
            bankCode = "微众收银台";
        }
        
        BillPaymentDTO billPaymentDTO = new BillPaymentDTO();
        billPaymentDTO.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        billPaymentDTO.setBank(bankCode);
        billPaymentDTO.setBillId(depositDTO.getId());
        billPaymentDTO.setMoney(depositDTO.getDepositAmount());
        billPaymentDTO.setPayType(payType);
        billPaymentDTO.setStatus(BillPaymentStatus.NONE); // 未支付
        billPaymentDTO.setBillType(com.logic.landseaserver.models.payment.PaymentConstant.BillType.RESERVE);
        Integer paymentId = billPaymentService.insertBillPaymentDTO(billPaymentDTO);
        
        String orderNo = "E1" + reqTime + paymentId;
        depositDTO.setOrderNo(orderNo);
        depositDTO.setPayMethod(payType);
        depositWriteMapper.updateByPrimaryKeySelectiveDTO(depositDTO);
        if (depositDTO.getDepositAmount() == null)
        {
            throw new BusinessException("订单没有价格");
        }
        
        // 更新订单号
        BillPayment billPayment = new BillPayment();
        billPayment.setId(paymentId);
        billPayment.setOrderNo(orderNo);
        billPayment.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
        billPaymentWriteMapper.updateByPrimaryKeySelective(billPayment);
        
        payinfo.setOrderId(orderNo);
        
        // 支付方式(网页)：微众-支付宝
        if (PaymentConstant.PayType.WEBANK_ALIPAY.equals(payType))
        {
            payinfo.setMerchantId(webankParam.getQrAliMerchantId());
            payinfo.setMerchantName(webankParam.getQrMerchantName());
            payinfo.setBrefMerchantName(webankParam.getQrMerchantAbbreviation());
            paydto = weBankService.getWeBankPayQR(payinfo);
            bankCode = "微众银行收单";
        }
        // 支付方式(网页)：微众-微信
        else if (PaymentConstant.PayType.WEBANK_WECHAT.equals(payType))
        {
            payinfo.setMerchantId(webankParam.getQrMerchantId());
            payinfo.setMerchantName(webankParam.getQrMerchantName());
            payinfo.setBrefMerchantName(webankParam.getQrMerchantAbbreviation());
            paydto = weBankService.getWeBankPayQR(payinfo);
            bankCode = "微众银行收单";
        }
        // 支付方式(网页)：微众-收银台
        else if (PaymentConstant.PayType.WEBANK_MOBILE.equals(payType))
        {
            payinfo.setMerchantId(webankParam.getwMerchantId());
            payinfo.setMerchantName(webankParam.getwMerchantName());
            payinfo.setBrefMerchantName(webankParam.getwMerchantAbbreviation());
            paydto = weBankService.getWeBankPay(payinfo);
            bankCode = "微众收银台";
        }
        
        return paydto;
    }
    
    @Override
    public void clearDeposit(Date createDate)
    {
        String createDateStr = DateUtil.convertDateTime(createDate);
        LOG.info("createDateStr is ：" + createDateStr);
        Map<String, String> params = new HashMap<>();
        params.put("status", DepositEnum._DS1.getCode());
        params.put("createDate", createDateStr);
        List<Deposit> dsList = depositReadMapper.queryComeDueDeposit(params);
        for (Deposit deposit : dsList)
        {
            LOG.info("deposit {} is comedue,userid is {}", deposit.getId(), deposit.getUserId());
            // delete deposit
            try
            {
                deleteDeposit(deposit.getId());
            }
            catch (BusinessException e)
            {
                LOG.error("deposit {} is comedue,userid is {},release room is BusinessException ",
                    deposit.getId(),
                    deposit.getUserId());
                LOG.error(e.getMessage());
            }
        }
    }
    
    @Override
    public List<Object> queryListForWechat()
        throws LandseaBusinessException, BusinessException
    {
        Integer systemId = SecurityUtils.getCurrentLogin().getUserId();
        if (systemId == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        User user = userService.get(systemId);
        if (user == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.CONTRACT_OFFLINE_CREATE_CUSTOMER_ISNULL);
        }
        return depositReadMapper.queryDepositByUserId(systemId);
    }
    
    @Override
    public String updatePayStatus()
        throws Exception
    {
        List<Deposit> dto = depositReadMapper.getUnpayedDeposit();
        List<String> errorMsg = new ArrayList<String>();
        List<String> excptionMsg = new ArrayList<String>();
        for (int i = 0; i < dto.size(); i++)
        {
            Deposit deposit = dto.get(i);
            CheckPayDTO payinfo = new CheckPayDTO();
            
            payinfo.setDepositId(deposit.getId());
            payinfo.setBusinessType(SystemCodeEnum.BUSINESS_TYPE_DEPOSIT.getCode());
            try
            {
                WeBankPayCheckDTO paydto = weBankService.checkPay(payinfo);
            }
            catch (LandseaException e)
            {
                errorMsg.add("预定id" + deposit.getId() + e.getErrorDesc());
            }
            catch (BusinessException e)
            {
                errorMsg.add("预定id" + deposit.getId() + e.getMessage());
            }
            catch (Exception e2)
            {
                excptionMsg.add("预定id" + deposit.getId() + e2.getMessage());
            }
        }
        JSONObject result = new JSONObject();
        result.put("status", 0);
        result.put("MSG", "同步预定支付信息");
        result.put("BusinessException", errorMsg);
        result.put("ExceptionMSG", excptionMsg);
        return result.toString();
    }
    
    @Override
    public Object queryPDFImg(Integer depositId)
        throws LandseaBusinessException
    {
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        SystemFile imgFile = null;
        if (userId == null || userId == -1)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        HashMap map = new HashMap();
        map.put("depositId",depositId);
        DepositPdfDTO dto = depositReadMapper.getDipositPdfDTO(map);
        if (dto == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_UPDATE_VALIDID_IS_NULL);
        }
        else
        {
            if (dto.getPdfImg() != null)
            {
                try
                {
                    imgFile = (SystemFile)fileService.get(dto.getPdfImg() + "");
                }
                catch (BusinessException e)
                {
                    LOG.error("queryPDFImg error.", e);
                }
            }
        }
        return imgFile;
    }
    
    @Override
    public void testCreatePDFImg()
        throws BusinessException
    {
        List<Deposit> depositList = depositReadMapper.queryPDFImgIsNull();
        for (Deposit ds : depositList)
        {
            SystemFile pdfFile = (SystemFile)fileService.get(ds.getPdfId() + "");
            // String localPath =
            // dipositPDFConfiguration.getLocal() + "/" + dipositPDFConfiguration.getDipositPath() + "/" +
            // pdfFile.getName();
            DepositPdfDTO dto = new DepositPdfDTO();
            dto.setPdfId(ds.getPdfId());
            dto.setPdfImg(ds.getPdfImg());
            dto.setId(ds.getId());
            createOrUpdateImg(dto, ds.getPdfId());
        }
    }
    
    @Override
    @Transactional
    public void releaseRoom(ReleaseRoomReq req)
        throws BusinessException
    {
        
        Integer userId = SecurityUtils.getCurrentLogin().getUserId();
        if (userId == null || userId == -1)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.TOKEN_IS_NULL);
        }
        DepositDTO depositDTO = depositReadMapper.getDepositDetail(req.getDepositId());
        
        // 判断是否已经释放过房源
        if (depositDTO.getHasEnd())
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_HAS_UPDATE_END);
        }
        
        // 判断是否已经释放过房源
        if (!depositDTO.getStatus().equals(DepositEnum._DS2.getCode())
            && !depositDTO.getStatus().equals(DepositEnum._DS4.getCode()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_HAS_TIME_END);
        }
        
        if (!depositDTO.getRoomAppendStatus().equals(RoomStatusCodeEnum.LRB2.getCode()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_ROOM_IS_END);
        }
        
        // 释放房源
        Room room = new Room();
        room.setId(depositDTO.getRoomId());
        room.setAppendStatus(RoomStatusCodeEnum.LRB1.getCode());
        room.updateCommonInfo(userId);
        projectAppartmentImpl.updateAppendStatus(room);
        
        // 标识定金结束路程
        Deposit deposit = new Deposit();
        deposit.setId(req.getDepositId());
        deposit.setHasEnd(true);
        deposit.setApplyRefund(req.getRefundMoney());
        deposit.updateCommonInfo(userId);
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
        
    }



    @Override
    public void posCallBack(DepositDTO depositDTO)
        throws BusinessException, LandseaException
    {
        Deposit deposit = depositReadMapper.selectByPrimaryKey(depositDTO.getId());
        boolean chapterFlag = deposit.getChapter();
        if (deposit == null)
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_UPDATE_VALIDID_IS_NULL);
        }
        if (StringUtils.isEmpty(depositDTO.getImageId()))
        {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_POS_IMG_IS_NULL);
        }
        // 将支付凭证更新
        deposit.setImageId(depositDTO.getImageId() == null ? null : depositDTO.getImageId());
        deposit.setPayMethod(depositDTO.getPayMethod() == null ? null : depositDTO.getPayMethod());
        deposit.setDepositAmount(depositDTO.getDepositAmount() == null ? null : depositDTO.getDepositAmount());
        deposit.setPaySn(depositDTO.getPaySn() == null ? null : depositDTO.getPaySn());
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
        depositWriteMapper.updateByPrimaryKeySelective(deposit);
    }

    @Override
    public void updateVersion(Integer depositId) throws Exception {
        //check是否符合变更的条件
        if(depositId!=null){
            DepositDTO dto = depositReadMapper.getDepositDetail(depositId);
            if(dto.getLatestVersion()){
                throw LandseaException.createException(LandseaErrorMessageEnum.CUSTOMER_VERSION_NOT_LASTEST);
            }else{
                UserFile userFile = new UserFile();
                CustomerVersion cv = customerService.getNewVersion(dto.getUserId());
                HashMap map = new HashMap();
                map.put("depositId",depositId);
                map.put("versionNum",cv.getVersionNumber());
                DepositPdfDTO pdfDto = depositReadMapper.getDipositPdfDTO(map);
                pdfDto.setChapter(false);
                pdfDto.setOprType(LandeaConstants.PdfOprType.CHANGE);
                userFile.setMainId(pdfDto.getId());
                userFile.setMainType(QueryUesdCodeType.DEPOSIT);
                userFile.setPdfId(pdfDto.getPdfId());
                userFile.setPdfImgId(pdfDto.getPdfImg());
                userFile.setUserId(dto.getUserId());
                userFile.setOldVersion(pdfDto.getUserVersion());
                userFile.setUserVersion(cv.getVersionNumber());
                userFile.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                //Step 1 重新生成PDF
                // 生成PDF文件
                Integer pdfId = productDipositPdf(pdfDto);
                if (pdfId != null)
                {
                    pdfDto.setPdfId(pdfId);
                    // 生成PDF图片
                    createOrUpdateImg(pdfDto, pdfId);
                }
                //Step 2 预定合同变更新增记录
                if(!dto.getStatus().equals(DepositEnum._DS1.getCode())){
                    userFileWriteMapper.insertSelective(userFile);
                }
                //Step 3更新版本信息
                Deposit ds = new Deposit();
                ds.setId(depositId);
                ds.setUserVersion(cv.getVersionNumber());
                ds.setChapter(false);
                ds.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());
                depositWriteMapper.updateByPrimaryKeySelective(ds);
            }
        }
    }

    @Override
    public List<UserFileDTO> queryHistoryVersions(Integer depositId) throws BusinessException {
        HashMap map = new HashMap();
        map.put("mainId",depositId);
        map.put("mainType", QueryUesdCodeType.DEPOSIT);
        List<UserFileDTO> userFileDTOs = userFileReadMapper.queryHistoryFile(map);
        if(userFileDTOs!=null){
            for(UserFileDTO dto:userFileDTOs){
                if (dto.getPdfId() != null)
                {
                    dto.setPdfPath(FileConverter.fromFileToDTO((SystemFile)this.fileService.get(dto.getPdfId())).getFullPath());
                }
                if (dto.getPdfImgId() != null)
                {
                    dto.setImgPath(FileConverter.fromFileToDTO((SystemFile)this.fileService.get(dto.getPdfImgId())).getFullPath());
                }
            }
        }
        return userFileDTOs;
    }

    @Override
    public Integer getChangeVersionCount(Integer prjId) {
        return depositReadMapper.queryChangeVersionCount(SecurityUtils.getCurrentLogin().getUserId(),prjId);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = {LandseaBusinessException.class,
            BusinessException.class, LandseaException.class, Exception.class})
    public void updateAuthCode(DepositDTO depositDTO) throws BusinessException, LandseaException {
        Deposit deposit = depositReadMapper.selectByPrimaryKey(depositDTO.getId());
        if (deposit == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.DEPOSIT_UPDATE_VALIDID_IS_NULL);
        }
        boolean chapterFlag = deposit.getChapter();
        // 判断房间是否有更换
        Integer newRoomId = depositDTO.getRoomId();
        Integer oldRoomId = deposit.getRoomId();
        boolean repdf = false;
        List<QueryCouponUesdDTO> oldCodes = new ArrayList<>();
        if(!deposit.getStatus().equals(DepositEnum._DS1.getCode())){
            //获取之前使用的授权码记录 除去定金授权码
            HashMap map = new HashMap();
            map.put("originalId", depositDTO.getId());
            oldCodes = couponUsedService.querypPersonalCouponList(map);
        }
        if (!newRoomId.equals(oldRoomId))
        {
            // 将原有房间状态改为空置，将目前预定房间状态改为预定
            Integer oldCounts = contractReadMapper.queryApartContractCounts(oldRoomId);
            if(oldCounts==0){
                Room oldRoom = new Room();
                oldRoom.setId(oldRoomId);
                oldRoom.setAppendStatus("LRB1");
                projectAppartmentImpl.updateAppendStatus(oldRoom);
            }
            Integer counts = contractReadMapper.queryApartContractCounts(depositDTO.getRoomId());
            if (counts == 0) {
                Room nowRoom = new Room();
                nowRoom.setId(newRoomId);
                nowRoom.setAppendStatus("LRB2");
                projectAppartmentImpl.updateAppendStatus(nowRoom);
            }
            repdf = true;
        }
        // 编辑操作
      //  if (StringUtils.isEmpty(depositDTO.getImageId()))
      //  {
            deposit = DepositDTO.convertToDeposit(depositDTO);
            // 生成PDF
            //DepositPdfDTO pdfDto = DepositPdfDTO.convertToDepositPdfDTO(deposit);
            //Updated by Daniel for 预定信息
            DepositPdfDTO pdfDto = DepositDTO.convertToDepositPdfDTO(depositDTO);
            CustomerCardDTO cardDTO = DepositDTO.convertToCustomerCardDto(depositDTO);
            pdfDto.setChapter(false);
            pdfDto.setCertificatesTypeCH(codeService.getCode(depositDTO.getCertificatesType()).getCodeDescZh());
            pdfDto.setProject(depositReadMapper.selectProject(depositDTO.getPrjId()));
            pdfDto.setRoom(depositReadMapper.selectRoomDTO(depositDTO.getRoomId()));
            pdfDto.setAddress(depositReadMapper.selectAddressDTO(depositDTO.getPrjId()));
            pdfDto.setPaymentModeName(codeService.getCode(depositDTO.getPaymentMode()).getCodeDescZh());
            pdfDto.setLeaseCH(codeService.getCode(depositDTO.getLease()).getCodeDescZh());
            pdfDto.setCustomerCardDTO(cardDTO);
            createOrUpdatePDF(pdfDto);
      //  }
        deposit.updateCommonInfo(SecurityUtils.getCurrentLogin().getUserId());// 调用版本等信息
        depositWriteMapper.updateByPrimaryKeySelective(deposit);

        //修改银行卡信息
        cardDTO.setSourceId(depositDTO.getId());
        cardDTO.setSourceType(QueryUesdCodeType.DEPOSIT);
        customerCardService.updateCustomerCard(cardDTO);
        //删除之前授权码使用记录
        couponUsedService.removeCouponUesd(depositDTO.getId(),QueryUesdCodeType.DEPOSIT);
       /* if(deposit.getStatus().equals(DepositEnum._DS1.getCode())){
            //草稿状态全部删除授权码
            couponUsedService.removeCouponUesd(depositDTO.getId(),QueryUesdCodeType.DEPOSIT);
        }else{
            //其余情况保留定金授权码，移除其他
            couponUsedService.removeCouponUesdSvDeposit(depositDTO.getId(),QueryUesdCodeType.DEPOSIT);
        }*/
        // 判断是否使用授权码
        boolean isUseCoupon = false;
        if (depositDTO.getAuthCodes() != null)
        {
            if(deposit.getStatus().equals(DepositEnum._DS1.getCode())){
                // check 数量是否正常
                couponUsedService.checkUesdAuthCode(QueryUesdCodeType.DEPOSIT,
                        depositDTO.getUserId(),
                        depositDTO.getAuthCodes());
            }
            AddCouponUesd couponUesds = new AddCouponUesd();
            couponUesds.setAuthCodes(depositDTO.getAuthCodes());
            couponUesds.setMainType(LandeaConstants.QueryUesdCodeType.DEPOSIT);
            couponUesds.setMainId(depositDTO.getId());
            couponUesds.setPrjId(depositDTO.getPrjId());
            couponUesds.setRoomId(depositDTO.getRoomId());
            couponUesds.setUserId(depositDTO.getUserId());
            couponUsedService.insertUesdList(couponUesds);
            isUseCoupon = true;
        }
        if(!deposit.getStatus().equals(DepositEnum._DS1.getCode())){
            //将之前的授权码改为未使用，投放数量
            if(oldCodes.size()>0){
                for(QueryCouponUesdDTO couponDTO:oldCodes){
                    //如果是定金 则不需要修改
                    if(couponDTO.getAuthFee().equals(BillTypeEnum.CTBI18.getCode())){
                        continue;
                    }
                    Coupon coupon = new Coupon();
                    coupon.setId(couponDTO.getId());
                    coupon.setStatus(LandeaConstants.CouponStatus.UNUSED);
                    coupon.updateCommonInfo(-1);
                    coupon.setCreatedBy(null);
                    coupon.setCreatedDtm(null);
                    //如果是个人授权码->修改使用数量
                    if (LandeaConstants.AppropriateType.PERSION.equals(couponDTO.getAppropriateType())) {
                        coupon.setUsedAmount(0);
                    }
                    couponWriteMapper.updateByPrimaryKeySelective(coupon);
                }
            }
            //将新的授权码改为已使用
            if(depositDTO.getAuthCodes()!=null && depositDTO.getAuthCodes().size()>0){
               authCodeService.updateCouponStatusAfterPay(QueryUesdCodeType.DEPOSIT, deposit.getId());
            }
        }
        // 重新生成独立账单
        // 先删除
        billIndependentService.removeDepositBalance(depositDTO.getId());
        // 备份到balace_sheet中的数据
        BalanceSheetRecord depositRecord = new BalanceSheetRecord();
        depositRecord.setBillId(depositDTO.getId());
        depositRecord.setProjectId(deposit.getPrjId());
        depositRecord.setRoomId(deposit.getRoomId());
        depositRecord.setBillType(BillType.RESERVE_BILL);
        // 预定合同ID就是自己的ID
        depositRecord.setContractId(deposit.getId());
        Room room1 = roomReadMapper.selectByPrimaryKey(deposit.getRoomId());
        depositRecord.setHouseNum(room1.getHouseNum());
        depositRecord.setStartTime(new Date());
        depositRecord.setEndTime(deposit.getAvailableDate());
        depositRecord.setReceivableMoney(deposit.getDepositAmount());
        depositRecord.setBillStatus(BillStatusEnum.BIST3.getCode());
        depositRecord.setExpenditureCode(BillTypeEnum.CTBI18.getCode());
        if (isUseCoupon)
        {
            // 如果使用授权码，则入授权码
            depositRecord.setExpenditure(BillTypeEnum.CTBI18.getName());
            depositRecord.setProduceType(ProduceType.AUTHCODE);
        }
        else
        {
            depositRecord.setExpenditure(BillTypeEnum.CTBI18.getName());
            depositRecord.setProduceType(ProduceType.PAY);
        }
        if(deposit.getStatus().equals(DepositEnum._DS2.getCode())){
            depositRecord.setPayTime(deposit.getPayDate());
            depositRecord.setAmountReceived(deposit.getDepositAmount());
            depositRecord.setBillStatus(BillStatusEnum.BIST2.getCode());
        }
        billIndependentService.insertBalanceSheet(depositRecord);
    }
}
